let currentEffect;
class Dep {
  constructor(val) {
    this.effectes = new Set();
    this._val = val;
  }

  get value() {
    this.depend();
    return this._val;
  }

  set value(newv) {
    this._val = newv;
    this.notice();
  }

  notice() {
    console.log('派发通知')
    this.effectes.forEach(effect => {
      effect();
    })
  }

  depend() {
    console.log('触发get方法，收集依赖', Dep.currentEffect)
    if(Dep.currentEffect) {
      this.effectes.add(Dep.currentEffect);
    }
  }
}
Dep.currentEffect = null;
// let dep = new Dep(19);
function EffectWatch(fn) {
  Dep.currentEffect = fn;
  //   
  console.log('触发一次调用')
  fn();
  Dep.currentEffect = null;
}

// let b;
// EffectWatch(function() {
//   b = dep.value + 10;
//   console.log(b);
// })

// dep.value = 20;
// dep.notice();
let getDep = (function getDep() {
  let targetMap = new Map();
  return function(target, key) {
    let targetItem = targetMap.get(target);
    if(!targetItem) {
      targetItem = new Map();
      targetMap.set(target, targetItem);
    }
    let depItem = targetItem.get(key);
    if(!depItem) {
      depItem = new Dep();
      targetItem.set(key, depItem);
    }
    return depItem;
  }
})();


function reactive(target) {
  return new Proxy(target, {
    get(target, key) {
      console.log('触发get方法');
      let dep = getDep(target, key);
      // 收集依赖
      dep.depend();
      return Reflect.get(target, key);
    },
    set(target, key, value) {
      console.log('触发set方法');
      let dep = getDep(target, key);
      let result = Reflect.set(target, key, value);
      dep.notice();
      return result;
    }
  })
}

var user = reactive({
  age: 10
})

var userA = 10;
EffectWatch(function() {
  console.log('收集依赖')
  // 这里会触发一次
  userA = user.age + 10;
  console.log('------userA------',userA);
})

user.age++;